Euler Problem 41

We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?


In [3]:
from itertools import permutations
from sympy import isprime

for v in permutations(range(7, 0, -1)):
    p = int(''.join(map(str, v)))
    if isprime(p):
        print(p)
        break


7652413

Explanation: Every pandigital number $N$ with 8 or 9 digits is divisible by 9, since the sum of the digits of $N$ is $1 + 2 + 3 + \cdots + 8 = 36$ or $1 + 2 + 3 + \cdots + 9 = 45$, respectively. Therefore, pandigital primes have at most 7 digits.

We use itertools.permutations to iterate through all permutations of the digits 1-7 in reverse order until we find a permutation that forms a prime number.